import { createSlice } from '@reduxjs/toolkit'
import { setToken as _setToken, getToken as _getToken, removeToken } from '@/utils/token'
import { getTokenApi, getUserInfoApi } from '@/apis/user'

const userStore = createSlice({
  name: 'user',
  initialState: {
    toten: _getToken() || '',
    userInfo: {}
  },
  reducers:{
    setToken(state, action){
      state.toten = action.payload
      _setToken(action.payload)
      
    },
    setUserInfo(state, action){
      state.userInfo = action.payload
    },
    clearUserInfo(state){
      state.toten = ''
      state.userInfo = {}
      removeToken()
    }
  }
})

export const { setToken, setUserInfo, clearUserInfo } = userStore.actions

export const getToken = (loginForm) => {
  return async (dispatch) => {
    const res = await getTokenApi(loginForm)
    dispatch(setToken(res.data.token))
  }
}

export const getUserInfo = () => {
  return async(dispatch) => {
    const res = await getUserInfoApi()
    dispatch(setUserInfo(res.data))
  }
}

export default userStore.reducer